package map;

/**
 * @author MeiZhongHao
 * @create_date 2022/11/24 17 15
 **/
public class Xmap<K, V> {

    private int capacity;

    private Node<K, V>[] nodes;

    public Xmap() {
        capacity = 16;
        nodes = new Node[capacity];
    }

    public void put(K key, V value) {
        int h = hashcode(key);
        for (Node<K, V> n = nodes[h]; n != null; n = n.next) {
            if (key.equals(n.key)) {
                n.value = value;
                return;
            }
        }
        Node<K, V> old = nodes[h];
        nodes[h] = new Node<>(key, value, old);
    }

    public V get(K key) {
        int h = hashcode(key);
        if (nodes[h] == null) {
            return null;
        }
        for (Node<K, V> n = nodes[h]; n != null; n = n.next) {
            if (key.equals(n.key)) {
                return n.value;
            }
        }
        return null;
    }

    class Node<K, V> {

        private K key;
        private V value;
        private Node<K, V> next;

        public Node() {
        }

        public Node(K key, V value, Node<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public int hashcode(K key) {
        //  & 0x7fffff 取绝对值
        return (key.hashCode() & 0x7fffff) % capacity;
    }

}
